window.onload = () => {
    let data = [
        {
            id: 1,
            url: 'https://img1.baidu.com/it/u=709085945,954063189&fm=253&fmt=auto&app=120&f=JPEG?w=1280&h=800',
            title: '标题1',
        },
        {
            id: 2,
            url: 'https://img2.baidu.com/it/u=623342223,221717372&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500',
            title: '标题22',
        },
        {
            id: 3,
            url: 'https://img1.baidu.com/it/u=3262750724,4229488744&fm=253&fmt=auto&app=120&f=JPEG?w=1422&h=800',
            title: '标题333',
        },
        {
            id: 4,
            url: 'https://ts1.cn.mm.bing.net/th/id/R-C.43dcf9c4dbac652f3beae4cce24e65a9?rik=DYkZ7jxRjwihvQ&riu=http%3a%2f%2fpic.bizhi360.com%2fbbpic%2f71%2f6971.jpg&ehk=2RwJIeeVPm%2fxUQn81A51v0PEVrtJrGO7i9fEk2ev5ZE%3d&risl=&pid=ImgRaw&r=0',
            title: '标题4444',
        },
    ];
    // 轮播图切换速度（动画时长）
    const rollingSpeed = 500;
    // 自动播放速度
    const playSpeed = 2000;

    // 轮播图内容
    function inner(param) {
        li = document.createElement('li');
        li.style['width'] = `${conWidth}px`;
        li.style['position'] = `relative`;
        li.style['background'] = `url("${data[param].url}") no-repeat center/100%`;
        li.innerHTML = `
            <h2>${data[param].title}</h2>
    
        `;
    }

    let swiper = document.querySelector('.swiper');
    let btn1 = document.querySelector('.swiper_Next');
    let btn2 = document.querySelector('.swiper_Prev');
    let ul = document.querySelector('.swiper>.swiper_Content');

    // 容器宽度
    let conWidth = swiper.clientWidth;

    // 跳过封面
    let ind = 1;

    // 由于有初始值ind = 1，切换方向时需要去掉该初始值
    let flag = false;

    // 动画锁
    var lock = false;

    // 解锁 动画结束后自动解锁 
    // bug：只能在所设置的动画时长结束后才可解锁
    // 当自动轮播时，动画执行中移入会生成解锁定时器，但动画此时已执行的动画时长比所设置的动画时长短，就会产生延迟（一定时间内按钮无法触发）
    let autoUnlock;
    function Unlock() {
        autoUnlock = setTimeout(function () {
            lock = false;
            // console.log('解锁');
        }, rollingSpeed)
    }

    // 封面（默认显示第一张图）
    let li = document.createElement('li');
    inner(0);
    ul.appendChild(li);

    // 保存指示器上一次位置
    let dotInd = 0;

    btn2.onclick = function () {
        if (lock) return;
        lock = true;
        // 判断上一次是否点击相反方向 是则 +1（进入下一张轮播图）
        ind = flag == true ? ind + 1 : ind;
        fn2(conWidth, rollingSpeed);
        ind++;
        flag = false;
        // 当前指示器高亮
        dot_active(ind - 1);
        Unlock(); // 解锁
        // 更新指示器位置为当前位置
        dotInd = ind - 1;
        // console.log('fn2：' + ind);
    }

    btn1.onclick = function () {
        if (lock) return;
        lock = true;
        // 判断上一次是否点击相反方向 是则 -1（进入上一张轮播图）
        ind = flag == false ? ind - 1 : ind;
        ind--;
        fn1(conWidth, rollingSpeed);
        flag = true;
        dot_active(ind);
        Unlock(); // 解锁
        // 更新指示器位置为当前位置
        dotInd = ind;
        // console.log('ind1：' + ind);
    }

    function fn2(x, speed = 1000) {
        if (ind >= data.length) ind = 0;

        inner(ind);
        ul.appendChild(li);

        ul.style['transition'] = `transform ${speed}ms`;
        ul.style['transform'] = `translateX(-${x}px)`;

        var stt = setTimeout(function () {
            ul.style['transition'] = `0s`;
            ul.style['transform'] = `translateX(0)`;
            ul.firstElementChild.remove();
        }, speed)
        // console.log('fn2:' + ind);
    }

    function fn1(x, speed = 1000) {
        if (ind < 0) ind = data.length - 1;

        inner(ind);
        ul.insertBefore(li, ul.firstElementChild);

        ul.style['transition'] = `0`;
        ul.style['transform'] = `translateX(-${x}px)`;

        setTimeout(function () {
            ul.style['transition'] = `transform ${speed}ms`;
            ul.style['transform'] = `translateX(0)`;
        }, 1)

        setTimeout(function () {
            ul.lastElementChild.remove();
            ul.style['transition'] = `0s`;
            ul.style['transform'] = `translateX(0)`;
        }, speed)
    }

    // 创建指示器
    let dotBox = document.querySelector('.dotBox');
    data.forEach(function (item, index) {
        let dot = document.createElement('div');
        dot.className = 'dot';
        dotBox.appendChild(dot);
        dot.onclick = function () {
            /* console.log(n);
            console.log(n, index); */
            if (lock) return;

            // 禁止重复点击同一指示点
            if (dotInd == index) return;

            ind = index;
            if (dotInd < index) {
                fn2(conWidth, rollingSpeed);
                flag = true;
            } else {
                fn1(conWidth, rollingSpeed);
                flag = false;
            }

            // 当前指示点高亮
            let d = document.querySelectorAll('.dot');
            d.forEach(function (item) {
                item.classList.remove('dot_active')
            })
            dot.classList.add('dot_active');

            flag = true;
            dotInd = ind;
            lock = true;
            Unlock();
        }
    })

    // 第一个指示点高亮
    var d = document.querySelectorAll('.dot');
    d[0].classList.add('dot_active');

    // 当前点击指示点高亮
    function dot_active(x) {
        d.forEach(function (item) {
            item.classList.remove('dot_active')
        })
        d[x].classList.add('dot_active');
    }

    // 初始自动轮播定时器
    let initAutoPlay = setInterval(function () {
        fn2(conWidth, rollingSpeed);
        ind++;
        dot_active(ind - 1);
        // 更新指示器位置为当前位置
        dotInd = ind - 1;
    }, playSpeed)

    let newAutoPlay;
    swiper.onmouseenter = function () {
        // 如果动画在进行，则锁定，并定时解锁
        if (ul.clientWidth != li.clientWidth) {
            lock = true;
            Unlock();
        }
        // 关闭所有自动轮播定时器
        clearInterval(initAutoPlay);
        if (newAutoPlay != 0) clearInterval(newAutoPlay);
    }

    swiper.onmouseleave = function () {
        // 鼠标移出 立即解锁 并 关闭自动延迟解锁
        lock = false;
        clearTimeout(autoUnlock);
        // 开启新自动轮播定时器
        newAutoPlay = setInterval(function () {
            ind = flag == true ? ind + 1 : ind;
            fn2(conWidth, rollingSpeed);
            ind++;
            dot_active(ind - 1);
            flag = false;
            // 更新指示器位置为当前位置
            dotInd = ind - 1;
        }, playSpeed)
    }

}